<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of fastmaintenance
 *
 * @author EaDeveloper
 */
class ComplexMaintenance extends Maintenance {

    public $gridmanager = null;
    public $fieldsConfig = array();
    public $pkFields = array();
    public $currentRecord = array();
    public $gridProperties = array();
    public $instanceName = "FastMaintenance";
    public $autoPK = false;
    public $encryptedCols = array();
    public $readOnlyCols = array();
    public $staticTabs = array();
    public $dynamicTabs = array();

    public function includeWidget() {
        
    }

    private function generaForma($ajax = false) {
        ?>
        <div id="dialog-cargando" style="width: auto; height: auto; vertical-align: middle; text-align: center; display: none">
            <img alt="Cargando"  id="img-cargando" src='../img/loading.gif' style="width: 100px; height: 100px" />
        </div>
        <form id="<?php echo $this->formName; ?>"
              name="<?php echo $this->formName; ?>"
              method="post" action="<?php echo CORE_PATH; ?>">
            <input type="hidden" id="module" name="module" value="<?php echo $this->instanceName; ?>" />
            <input type="hidden" id="pkfield" name="pkfield" value="<?php echo $this->pkFields[0]; ?>" />
            <input type="hidden" id="oper" name="oper" value="get" />
            <input type="hidden" id="ajax" name="ajax" value="0" />
            <input type="hidden" id="mode" name="mode" value="new" />
            <div id="mant_head">
                <div id="titulo"><?php echo $this->tittle; ?></div>
                <div id="botones">
                    <button id="cmdDel" title="Eliminar Registro" type="button" onclick="javascript:setDelMode();">
                        <img alt="Eliminar Registro"  src="../imgv2/actions/edit-delete.png" /></button>
                    <button id="cmdNew" title="Nuevo Registro" type="button" onclick="javascript:setNewMode();">
                        <img alt="Nuevo Registro"  src="../imgv2/actions/document-new.png" /></button>
                    <button id="cmdOk" title="Guardar Registro" type="button"  onclick="javascript:sendFormData();">
                        <img alt="Guardar Registro"  src="../imgv2/actions/document-save.png" />
                    </button>
                </div>
            </div>
            <div id="tabs">
                <ul>
                    <?php foreach ($this->staticTabs as $k => $tab) {
                        ?>
                        <li><a href="#tab1"><?php echo $tab; ?></a></li>
                    <?php } ?>
                    <?php foreach ($this->dynamicTabs as $k => $tab) { ?>
                        <li><a href="#_tab_<?php echo $k; ?>"><?php echo $tab; ?></a></li>
                    <?php } ?>
                </ul>
                <?php foreach ($this->staticTabs as $t => $tab) { ?>
                    <div class="form-container" id="_tab_<?php echo $k; ?>" style="height: auto !important;">
                        <fieldset>
                            <?php
                            $campos = $this->fieldsConfig[$t];
                            foreach ($campos as $k => $v) {
                                $defValues = array();

                                if (is_array($v)) {
                                    $label = $v[0];
                                    $type = $v[1];
                                    if (is_array($type)) {
                                        $defValues = $type;
                                    }
                                } else {
                                    $label = $v;
                                    $type = "text";
                                }
                                ?><div><label><?php echo $label; ?></label>
                                    <?php if (count($defValues) > 0) { ?>
                                        <select name="<?php echo $k; ?>" id="<?php echo $k; ?>">
                                            <option value="">-</option>
                                            <?php
                                            foreach ($defValues as $val => $lab) {
                                                $t = "";
                                                if (isset($this->currentRecord[$k]) && $this->currentRecord[$k] == $val) {
                                                    $t = 'selected="selected"';
                                                }
                                                ?>
                                                <option <?php echo $t; ?> value="<?php echo $val ?>"><?php echo $lab; ?> </option>
                                            <?php } ?>
                                        </select>
                                        <?php
                                    } else {
                                        $val = $this->currentRecord[$k];
                                        if (isset($this->encryptedCols[$k])) {
                                            $val = "";
                                        }
                                        ?>
                                        <input type="<?php echo $type; ?>" name="<?php echo $k; ?>" value="<?php echo $val; ?>" id="<?php echo $k; ?>" />
                                    <?php } ?>
                                </div>
                            <?php } ?>
                        </fieldset>
                        <?php
                        $this->includeWidget();
                        ?>
                    </div>
                <?php } ?>
                <?php foreach ($this->dynamicTabs as $k => $tab) { ?>
                    <div class="form-container" id="_tab_<?php echo $k; ?>">
                        <fieldset>
                            <?php $this->builder->build($this->table, $this->currentRecord[$this->pkFields[0]], $k); ?>
                        </fieldset>
                    </div>
                <?php } ?>
            </div>
            <script type="text/javascript">
                jQuery("#tabs").tabs();
                setNewMode();
            </script>
        </form>
        <?php
    }

    private function generaGrid() {
        $cols = $this->fieldsConfig[0];
        $colNames = array_keys($cols);
        $colsLabel = array();
        $colModel = array();
        foreach (array_values($cols) as $value) {
            if (is_array($value)) {
                $value = $value[0];
            }
            $colsLabel[] = $value;
        }
        foreach ($colNames as $c) {
            $colModel[] = array("name" => $c, "index" => $c);
        }
        $this->cfgGrid = array(
            "url" => CORE_PATH . "?module=$this->instanceName&oper=gridop&" . AJAX_INDICATOR . "=true",
            "datatype" => "json",
            "height" => "100%",
            "autowidth" => true,
            "colNames" => $colsLabel,
            "colModel" => $colModel,
            "rowNum" => "20",
            "rowTotal" => "2000",
            "rowList" => explode(",", "20,40,50"),
            "mtype" => "POST",
            "gridview" => true,
            "pager" => "_pager_",
            "sortname" => $colNames[0],
            "viewrecords" => true,
            "sortorder" => "asc",
            "toolbar" => array(true, "top"),
            "caption" => "Listado Registros"
        );
        ?>

        <table id="_grid_"></table>
        <div id="_pager_" ></div>
        <script type="text/javascript">
            var opts=<?php echo json_encode($this->cfgGrid); ?>;
            opts.onSelectRow=selectListener;
            jQuery("#_grid_").jqGrid(opts);
            jQuery("#_grid_").jqGrid('filterToolbar');
        </script>
        <?php
    }

    public function saveRec() {
        $colNames = array_keys($this->fieldsConfig);
        $data = array();
        foreach ($colNames as $p) {
            if ($p != $this->pkFields[0] || !$this->autoPK) {
                $val = getParam($p);
                if (isset($this->encryptedCols[$p])) {
                    $val = md5($val);
                }
                $data[$p] = sqlValue($val, "text");
            }
        }
        $pkcol = $this->pkFields[0];
        $this->db->query_insert($this->table, $data);
    }

    public function delRec() {
        $pk = sqlValue(getParam($this->pkFields[0]), "text");
        $this->db->query_delete($this->table, $this->pkFields[0] . "=$pk");
    }

    public function updateRec() {
        $colNames = array_keys($this->fieldsConfig);
        $data = array();
        foreach ($colNames as $p) {
            if ($p != $this->pkFields[0]) {
                $val = getParam($p);
                if (isset($this->encryptedCols[$p])) {
                    $val = md5($val);
                }
                $data[$p] = sqlValue($val, "text");
            }
        }
        $pkcol = $this->pkFields[0];
        $where = "$pkcol=" . sqlValue(getParam($pkcol), "text");
        $this->db->query_update($this->table, $data, $where);
    }

    private function getRecord() {
        $w = $this->getWhere();
        $r = $this->db->queryToArray("select * from $this->table $w ");
        $this->currentRecord = $r[0];
    }

    private function dispatchGridRequest() {
        if ($this->gridmanager == null) {
            $cols = $this->fieldsConfig[0];
            $colNames = array_keys($cols);
            $this->gridmanager = new JGridGenerator();
            $this->gridmanager->table = $this->table;
            $this->gridmanager->fields = $colNames;
            $this->gridmanager->pk = $this->pkFields[0];
            $this->gridmanager->db = $this->db;

            $a = array();
            foreach ($colNames as $c) {
                $a[$c] = "text";
            }
            $this->gridmanager->colTypes = $a;
        }
        $this->gridmanager->main();
    }

    private function getWhere() {
        $where = "";
        foreach ($this->pkFields as $pk) {
            $v = getParam($pk);
            $where.="$pk=" . sqlValue($v, "text");
        }
        return !isEmpty($where) ? "where $where" : "";
    }

    private function showPage() {
        ?>
        <div id="maintenancecontainer" style="height: auto;">
            <div id="formpanel">
                <?php $this->generaForma(); ?>
            </div>
            <div id="gridpanel">
                <?php $this->generaGrid(); ?>
            </div>
        </div>
        <?php
    }

    public function main() {
        if ($this->builder == null) {
            $this->builder = new InputBuilder();
            $this->builder->db = $this->db;
            $this->builder->loadFields($this->table);
        }
        $this->loadDynValidations();

        if (!isEmpty(getParam("oper"))) {
            switch (getParam("oper")) {
                case "add": {
                        $this->saveRec();
                        break;
                    }
                case "upd": {
                        $this->updateRec();
                        break;
                    }
                case "del": {
                        $this->delRec();
                        break;
                    }
                case "get": {
                        $this->getRecord();
                        $this->generaForma(true);
                        break;
                    }
                case "gridop": {
                        $this->dispatchGridRequest();
                        break;
                    }
            }
        } else {
            $this->showPage();
        }
    }

}
?>
